package com.cloudkinto.controller.stock;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.extentity.StockSnapshotPageDto;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.shop.impl.ShopServiceImpl;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.stock.vo.StockRecordDetailRes;
import com.cloudkinto.service.stock.vo.StockRecordReq;
import com.cloudkinto.service.stock.vo.StockTurnoverRatePageRes;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import com.cloudkinto.service.stock.vo.record.StockRecordSendReq;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-10
 */
@RestController
@Api(tags = "库存管理模块")
@RequestMapping("/api/stockRecord")
public class StockRecordController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(StockRecordController.class);

    @Autowired
    private StockRecordService service;
    @Autowired
    private ShopService shopService;


    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看库存信息", notes = "根据id查看产品")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordDetailRes.class)})
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id, getCompanyId()));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCompanyId(), getCurrentUserId());
    }

    @UserSessionRequired
    @PostMapping("sendOutInit")
    @ApiOperation(value = "发货初始化", notes = "发货初始化")
    public SingleResult sendOutInit() {
//        Long companyId = getCompanyId();
//        Long userId = getCurrentUserId();
        return service.sendOutInit();
    }

    @UserSessionRequired
    @PostMapping("sendOut")
    @ApiOperation(value = "发货", notes = "发货")
    public SingleResult sendOut(@RequestBody @Validated StockRecordSendReq req) {
        Long companyId = getCompanyId();
        Long userId = getCurrentUserId();
        return service.sendOut(req, userId, companyId);
    }

    @UserSessionRequired
    @PostMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> listPage(@RequestBody @Validated StockRecordReq req) {
        Map map = new HashMap<>();
        map.put("keyword", req.getKeyword());
        map.put("shopId", req.getShopId());
        map.put("inStock", req.getInStock());
        map.put("storageId", req.getStorageId());
        map.put("productType", req.getProductType());
        map.put("companyId", getCompanyId() + "");
        map.put("current", req.getCurrent());
        map.put("pageSize", req.getPageSize());
        if (StringUtils.isBlank(req.getShopId())) {
            List<Map> mapList = shopService.selectShopListInit(getCurrentUserId(), getCompanyId());
            map.put("shopId", mapList.stream().map(map1 -> String.valueOf(map1.get("id"))).collect(Collectors.joining(",")));
        }
        return service.getListPage(map);
    }


    @UserSessionRequired
    @PostMapping("/exportStockRecord")
    @ApiOperation(value = "导出库存明细 按单号")
    public void exportStockRecord(@RequestBody @Validated StockRecordReq req, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.getKeyword());
        map.put("shopId", req.getShopId());
        map.put("storageId", req.getStorageId());
        map.put("productType", req.getProductType());
        map.put("companyId", getCompanyId() + "");
        service.exportStockRecord(map, response);
    }


    @UserSessionRequired
    @GetMapping("/turnoverRateList")
    @ApiOperation(value = "库存周转率列表", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "keyword", value = "模糊搜索"), @ApiImplicitParam(name = "productType", value = "商品分类")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockTurnoverRatePageRes.class)})
    public PageResult<StockTurnoverRatePageRes> turnoverRateList(String shopId, String current,
                                                                 String startDate, String endDate,
                                                                 String pageSize, String keyword, String productType) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", keyword);
        if (StringUtils.isNotBlank(shopId)) {
            map.put("shopId", shopId);
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        if (StringUtils.isNotBlank(startDate)) {
            map.put("startDate", startDate);
        } else {
            map.put("startDate", TimeUtils.getCurrentDateFormat(-7));
        }
        if (StringUtils.isNotBlank(endDate)) {
            map.put("endDate", endDate);
        } else {
            map.put("endDate", TimeUtils.getCurrentDateFormat());
        }
        if (StringUtils.isNotBlank(productType))
            map.put("productType", productType);
//        map.put("storageId", storageId);
        if (companyId != null)
            map.put("companyId", companyId + "");
        map.put("current", current);
        map.put("pageSize", pageSize);
        return service.turnoverRateList(map);
    }

    @UserSessionRequired
    @GetMapping("/turnoverRateTotal")
    @ApiOperation(value = "库存总周转率", notes = "")
    public SingleResult turnoverRateList(String shopId,
                                         String startDate, String endDate) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(shopId)) {
            map.put("shopId", shopId);
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        if (StringUtils.isNotBlank(startDate)) {
            map.put("startDate", startDate);
        } else {
            map.put("startDate", TimeUtils.getCurrentDateFormat(-7));
        }
        if (StringUtils.isNotBlank(endDate)) {
            map.put("endDate", endDate);
        } else {
            map.put("endDate", TimeUtils.getCurrentDateFormat());
        }
        if (companyId != null)
            map.put("companyId", companyId + "");
        return service.turnoverRateTotal(map);
    }

    /********************库存快照模块********************/

    @UserSessionRequired
    @GetMapping("/stockSnapshotPage")
    @ApiOperation(value = "库存快照查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "commoditySku", value = "OMS SKU"),
            @ApiImplicitParam(name = "startDate", value = "开始日期"),
            @ApiImplicitParam(name = "endDate", value = "结束日期")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockSnapshotPageDto.class)})
    public PageResult stockSnapshotPage(String current, String pageSize, String storageId, String commoditySku, String startDate, String endDate) {
        Map<String, String> map = new HashMap<>();
        map.put("commoditySku", commoditySku);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("storageId", storageId);
        map.put("companyId", getCompanyId() + "");
        map.put("current", current);
        map.put("pageSize", pageSize);
        return service.getStockSnapshotPage(map);
    }

    @UserSessionRequired
    @GetMapping("/exportExcel")
    @ApiOperation(value = "库存快照导出Excel")
    @ApiImplicitParams({@ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "commoditySku", value = "OMS SKU"),
            @ApiImplicitParam(name = "startDate", value = "开始日期"),
            @ApiImplicitParam(name = "endDate", value = "结束日期")})
    public SingleResult exportExcel(String storageId, String commoditySku, String startDate, String endDate) throws IOException {
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = simpleDateFormat.format(new Date());
        String fileName = "库存快照" + time + ".xls";
        map.put("commoditySku", commoditySku);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("storageId", storageId);
        map.put("companyId", getCompanyId() + "");
        return SingleResult.success(service.exportExcel(map, fileName));
    }


    /**
     * 真实得先进先出库龄
     * @param req
     * @param response
     */
    @UserSessionRequired
    @PostMapping("/exportProductStockDetail")
    @ApiOperation(value = "导出库存明细 按单号")
    public void exportProductStockDetail(@RequestBody @Validated StockRecordReq req, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.getKeyword());
//        map.put("shopId", req.getShopId());
        map.put("storageId", req.getStorageId());
        map.put("productType", req.getProductType());
        map.put("companyId", getCompanyId() + "");
        service.exportProductStockDetailFalse(map, response);
    }




}

